<script setup lang="ts">
const onDivChange = (evt: Event) => {
    let el = evt.target as any;
    for (let i = 0; i < el.childNodes.length; i++) {
        if (el.childNodes[i].tagName == undefined) {
            createTextByNode(el.childNodes[i]);
            i--;
        }
    }
}

const getValues = (): string[] => {
    return [];
}

const createTag = (evt: KeyboardEvent) => {
    if (evt.key != 'enter' && evt.key != ' ') {
        return;
    }
    const selection1 = window.getSelection() as any; // 获取当前选区
    if (selection1 == null || selection1.baseNode == null) {
        return;
    }
    createTextByNode(selection1.baseNode);
}

const createTextByNode = (node: any) => {
    let text = node.textContent.trim();
    if (text == "") {
        node.parentNode.removeChild(node);
        return;
    }
    appendValueTag(node, text);
    const parentNode = node.parentNode;
    parentNode.removeChild(node);
    const range = document.createRange(); // 创建一个新的范围对象
    range.selectNodeContents(parentNode); // 将范围设置为整个内容
    range.collapse(false); // 将光标设置在内容的末尾
    const selection = window.getSelection(); // 获取当前选区
    if (selection != null) {
        selection.removeAllRanges(); // 清除当前选区
        selection.addRange(range); // 添加新的选区
    }
}

const appendValueTag = (node: any, text: string) => {
    let tagEl = document.createElement("span");
    tagEl.className = "app-secs-value";
    tagEl.contentEditable = "false";
    let tagEl2 = document.createElement("span");
    tagEl2.className = "app-secs-value-inner";
    let tagEl2_1 = document.createElement("span");
    tagEl2_1.innerText = text;
    tagEl2.appendChild(tagEl2_1);
    let tagEl2_2 = document.createElement("i");
    tagEl2_2.className = "el-icon";
    tagEl2_2.innerHTML = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1024 1024\"><path fill=\"currentColor\" d=\"M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z\"></path></svg>";
    tagEl2_2.onclick = function (evt: MouseEvent) {
        let el = evt.target as any;
        el.parentNode.parentNode.parentNode.parentNode.removeChild(el.parentNode.parentNode.parentNode);
    }
    tagEl2.appendChild(tagEl2_2);
    tagEl.appendChild(tagEl2);
    node.parentNode.insertBefore(tagEl, node);
};

defineExpose({ getValues });
</script>
<template>
    <div style="height:160px;width:300px;border:1px solid #EFEFEF;outline: none;padding:5px" contenteditable="true"
        @keyup="createTag" @blur="onDivChange">
    </div>
</template>